import onload from '../utils/onload'
import getLastEvent from '../utils/getLastEvent'
import getSelector from '../utils/getSelector'

export function timing() {
    let FMP, // First Meaningful Paint(首次有意义绘制)
        LCP // Largest Contentful Paint)(最大内容渲染)
    // https://developer.mozilla.org/zh-CN/docs/Web/API/PerformanceObserver/observe api地址
    if (PerformanceObserver) {
        new PerformanceObserver((entryList, observer) => {
            let perfEntries = entryList.getEntries()
            FMP = perfEntries[0]
            observer.disconnect() // 不再观察
        }).observe({ entryTypes: ['element'] }) // 观察页面中的意义的元素

        new PerformanceObserver((entryList, observer) => {
            let perfEntries = entryList.getEntries()
            LCP = perfEntries[0]
            observer.disconnect() // 不再观察
        }).observe({ entryTypes: ['largest-contentful-paint'] }) // 页面绘制最大内容区域

        new PerformanceObserver((entryList, observer) => {
            let lastEvent = getLastEvent()
            let firstInput = entryList.getEntries()[0]
            console.log('FID', firstInput)
            if (firstInput) {
                // processingStart开始处理的时间 startTime开点击的时间 差值就是处理的延迟
                let inputDelay = firstInput.processingStart - firstInput.startTime
                let duration = firstInput.duration // 处理的耗时
                if (inputDelay > 0 || duration > 0) {
                    let log = {
                        kind: 'experience', // 用户体验指标
                        type: 'firstInputDelay', // 首次输入延迟
                        inputDelay, // 延时的时间
                        duration, // 处理的时间
                        startTime: firstInput.startTime,
                        selector: lastEvent ? getSelector(lastEvent.path || lastEvent.target) : ''
                    }

                    console.log('firstInputDelay-log', log)
                }

            }
            observer.disconnect() // 不再观察
        }).observe({ type: 'first-input', buffered: true }) // 首次输入延迟
    }

    onload(function() {
        setTimeout(function() {
            let performance = window.performance || window.mozPerformance || window.msPerformance || window.webkitPerformance
            let log = {
                 // 网络建连
                pervPage: filterTime(timing.fetchStart, timing.navigationStart), // 上一个页面
                redirect: filterTime(timing.responseEnd, timing.redirectStart), // 页面重定向时间
                dns: filterTime(timing.domainLookupEnd, timing.domainLookupStart), // DNS查找时间
                connect: filterTime(timing.connectEnd, timing.connectStart), // TCP建连时间
                network: filterTime(timing.connectEnd, timing.navigationStart), // 网络总耗时

                // 网络接收
                send: filterTime(timing.responseStart, timing.requestStart), // 前端从发送到接收到后端第一个返回
                receive: filterTime(timing.responseEnd, timing.responseStart), // 接受页面时间
                request: filterTime(timing.responseEnd, timing.requestStart), // 请求页面总时间

                // 前端渲染
                dom: filterTime(timing.domComplete, timing.domLoading), // dom解析时间
                loadEvent: filterTime(timing.loadEventEnd, timing.loadEventStart), // loadEvent时间
                frontend: filterTime(timing.loadEventEnd, timing.domLoading), // 前端总时间

                // 关键阶段
                load: filterTime(timing.loadEventEnd, timing.navigationStart), // 页面完全加载总时间
                domReady: filterTime(timing.domContentLoadedEventStart, timing.navigationStart), // domready时间
                interactive: filterTime(timing.domInteractive, timing.navigationStart), // 可操作时间
                ttfb: filterTime(timing.responseStart, timing.navigationStart),  // 首字节时间
            }
            console.log('timing-log', log)
            
        }, 3000) // 延迟3秒获取数据，准确性更高
    })
}

export const filterTime = (a, b) => {
    return (a > 0 && b > 0 && (a - b) >= 0) ? (a - b) : undefined
}